package com.ljt.yupictureddd.shared.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ljt.yupictureddd.shared.manager.auth.SpaceUserAuthManager;
import com.ljt.yupictureddd.shared.manager.auth.model.SpaceUserPermissionConstant;
import com.ljt.yupictureddd.domain.picture.entity.Picture;
import com.ljt.yupictureddd.domain.space.entity.Space;
import com.ljt.yupictureddd.domain.user.entity.User;
import com.ljt.yupictureddd.domain.space.valueobject.SpaceTypeEnums;
import com.ljt.yupictureddd.application.service.PictureApplicationService;
import com.ljt.yupictureddd.application.service.SpaceApplicationService;
import com.ljt.yupictureddd.application.service.UserApplicationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * WebSocket拦截器，在建立连接前需要进行校验
 */
@Slf4j
@Component
@AllArgsConstructor
public class WsHandShakeInterceptor implements HandshakeInterceptor {


    private final UserApplicationService userApplicationService;
    private final PictureApplicationService pictureApplicationService;
    private final SpaceApplicationService spaceApplicationService;
    private final SpaceUserAuthManager spaceUserAuthManager;


    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 获取当前用户
        HttpServletRequest httpServletRequest = null;
        if (request instanceof ServletServerHttpRequest) {
            // 获得http请求
            httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        }
        // 获得参数
        String pictureId = httpServletRequest.getParameter("pictureId");
        if (StrUtil.isBlank(pictureId)) {
            log.error("缺少图片参数,拒绝握手");
            return false;
        }
        // 获取当前登录用户
        User loginUser = userApplicationService.getLoginUser(httpServletRequest);
        if (ObjUtil.isNull(loginUser)) {
            log.error("用户未登录,拒绝握手");
            return false;
        }
        // 判断存在
        Picture oldPicture = pictureApplicationService.getById(pictureId);
        if (ObjUtil.isNull(oldPicture)) {
            log.error("图片不存在,拒绝握手");
            return false;
        }
        // 判断是不是团队空间
        Long spaceId = oldPicture.getSpaceId();
        Space space = null;
        if (spaceId != null) {
            space = spaceApplicationService.getById(spaceId);
            // 如果是团队空间,并且有编辑者权限,才能建立连接.
            if (ObjUtil.notEqual(space.getSpaceType(), SpaceTypeEnums.TEAM.getValue())) {
                log.error("不是团队空间,拒绝握手");
                return false;
            }
            // 判断是有具有权限
            // 校验用户是否有编辑当前图片的权限
        }
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        if (!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
            log.error("没有图片编辑权限,拒绝握手");
            return false;
        }
        // 设置用户信息等属性到WebSocket对话中(只要在attributes插入就好可)
        attributes.put("user",loginUser);
        attributes.put("userId",loginUser.getId());
        attributes.put("pictureId",Long.valueOf(pictureId));//别忘了传入pictureId
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
